package com.joker;

import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;
import java.io.IOException;
import java.util.concurrent.CountDownLatch;

public class ZooKeeperBasicExample {
    private static final String ZK_ADDRESS = "106.12.75.108:2181";
    private static final int SESSION_TIMEOUT = 5000;
    private static CountDownLatch connectedSignal = new CountDownLatch(1);

    public static void main(String[] args) throws IOException, InterruptedException {
        ZooKeeper zk = connect();
        
        // 执行一些操作...
        System.out.println("连接状态: " + zk.getState());
        
        // 关闭连接
        zk.close();
    }

    public static ZooKeeper connect() throws IOException, InterruptedException {
        ZooKeeper zk = new ZooKeeper(ZK_ADDRESS, SESSION_TIMEOUT, new Watcher() {
            @Override
            public void process(WatchedEvent event) {
                if (event.getState() == Event.KeeperState.SyncConnected) {
                    connectedSignal.countDown();
                    System.out.println("成功连接到ZooKeeper服务器");
                }
            }
        });
        
        connectedSignal.await();
        return zk;
    }
}